<template>
  <view class="contain">
    <view v-if="!isRefresh" :class="refreshClass" class="fixed-top flex h-44 bg-color-f3"
          :style="{'padding-top': top + 'px'}">
      <view @click="back(1)" class="flex f-a-c f-j-c padding-lr12 van-icon van-icon-arrow-left f20-size"></view>
      <view class="flex flex-1 f-a-c margin-r4">
        <view @click="go('/pagesA/search/index')" class="flex flex-1 f-a-c h-32 bg-color-w b-radius-30 padding-lr10">
          <text class="flex f-a-c van-icon van-icon-search f16-size margin-r4"></text>
          <text class="t-color-9">{{ i18n['搜索商品'] }}</text>
        </view>
      </view>
      <view @click="go('/pagesA/chat/chat?id='+shop.memberId+'&goodsId=' + goods.id)"
            class="flex f-a-c f-j-c padding-lr5 van-icon van-icon-chat-o f20-size"></view>
      <view @click="like" :class="isLike ? 't-color-r van-icon-star' : 'van-icon-star-o '"
            class="flex f-a-c f-j-c padding-lr5 van-icon van-icon-star-o f20-size"></view>
      <view @click="$refs.menuBtn.open()" class="flex f-a-c f-j-c padding-lr5 van-icon van-icon-bars f20-size"></view>
      <view class="padding-lr2"></view>
      <xcx-header></xcx-header>
    </view>
    <view :style="{'padding-top': top+44+'px'}"></view>
    <view style="position: relative;">
      <u-image :src="options.mainImg+'?'+globalImageProcessingSuffix" mode="widthFix" @click="preImg(options.mainImg)">
        <view slot="error" style="font-size: 24rpx;">
          <u-image class="flex  f-s-0 w-100 h-80 bg-img b-radius-10" border-radius="14px"
                   :src="'https://img.fscmkjznb.com/static/noImg.jpeg'+'?'+globalImageProcessingSuffix" alt=""/>
        </view>
      </u-image>
      <view
          style="margin-top: -84px;background-color: white;border-top-left-radius: 30px; border-top-right-radius: 30px;z-index: 2;position: absolute">
        <view style="margin-left: 10px">
          <hm-cover-card :options="options" @clickItem="chooseItem"></hm-cover-card>
        </view>
        <video-index :goodsId="id"  :recommend="recommend" ref="videoList"
                     :trailerLink="options.trailerLink" :shopId="shopId"></video-index>
      </view>
    </view>

    <menu-btn ref="menuBtn"></menu-btn>
  </view>
</template>
<style scoped>

@import url('../../static/css/shops/detail.css');
</style>
<script>
import HmCoverCard from '../../pagesA/components/hm-cover-card/index.vue'
import videoIndex from '../../pages/find/index.vue';
import couponList from '../../pages/common/couponlist.vue';


const API = require('../../utils/api/shops.js').default;
const $ = require('../../utils/api.js');
let self;
let inter;
export default {
  data() {
    return {
      globalImageProcessingSuffix: '',
      recommend: null,
      options: {
        mainImgArray: [],
        mainImg: '',
        title: '',
        price: '',
        shoucang: '',
        trailerLink: ""
      },
      isRefresh: false,
      refreshClass: [''],
      top: uni.getStorageSync('bartop') ? uni.getStorageSync('bartop') : 0,
      isIphonex: uni.getStorageSync('isIphonex') ? uni.getStorageSync('isIphonex') : false,
      goods: '',
      id: '',
      banner: [],
      bannerIndex: 0,
      goodsParams: [],
      // skuInfoList: [],//规格属性
      skuList: [],//规格价格表
      // chooseSkuList: [],
      // sku: '',//选中规格后的商品信息
      attrSymbolPath: '',
      num: 1,
      shop: '',
      isLike: false,
      fahuo: '',
      couponList: [],
      commentList: [],
      now: 0,
      now1: 0,
      day: 0,
      hour: 0,
      minute: 0,
      second: 0,
      group: '',
      groupId: '',
      joinGroupId: '',
      isShareGroup: false,
      groupList: [],
      pintuanNum: 0,
      groupListConfig: [],
      groupConfig: '',
      shopId: null
    };
  },
  onLoad: function (options) {
    self = this;
    this.globalImageProcessingSuffix = getApp().globalData.globalImageProcessingSuffix;
    this.id = options.id ? options.id : 6;
    this.shopId = options.shopId
    this.joinGroupId = options.joinId ? options.joinId : '';
  },
  onShow() {
    this.init();
  },
  methods: {
    preImg(item) {
      uni.previewImage({
        urls: [item], // 需要预览的图片链接列表
      });
    },
    chooseItem(item) {
      uni.previewImage({
        urls: [item], // 需要预览的图片链接列表
      });
    },
    getImgs(imgs) {
      if (!imgs) {
        return;
      }
      if (imgs.indexOf('|') > 0) {
        return imgs.split('|')
      } else {
        return [imgs]
      }
    },

    chooseGroupConfig(info) {
      if (this.group == '') {//空则可选择自己的阶梯，非空时加入别人的团
        this.groupConfig = info;
      }
    },

    clearData() {
      if (this.isShareGroup) {
        return;
      }//分享链接一直保持参团信息
      this.group = '';
      this.groupId = '';
    },

    isMS() {
      return self.goods.type == 2
    },
    isPT(type) {//1普通拼团>>2阶梯拼团
      if (type) {
        if (type == 1) {
          return self.goods.type == 3 && self.goods.groupType == 1
        }
        if (type == 2) {
          return self.goods.type == 3 && self.goods.groupType == 2
        }
      } else {
        return self.goods.type == 3
      }
    },
    getMStype(type) {
      if (type == 'start') {
        return self.now < self.goods.seckillBeginTime
      }
      if (type == 'in') {
        return self.now >= self.goods.seckillBeginTime && self.now <= self.goods.seckillEndTime
      }
      if (type == 'end') {
        return self.now > self.goods.seckillEndTime
      }
    },
    getCommonList() {
      $.ajax({
        url: API.goodsCommentListApi,
        data: {
          page: 1,
          pageSize: 10,
          goodsId: self.id,
          goodsComment: '',//1好评>>2中评>>3差评>>4有图
        },
        method: 'GET',
        success(res) {
          self.commentList = res.data.list ? res.data.list : [];
        }
      })
    },

    groupBuy(type) {
      if (this.attrSymbolPath == '') {
        $.$toast(self.i18n['请选择正确的规格']);
        return;
      }
      //type1，单独购买，2创建拼团,3有拼团信息的
      if (type == 1) {
        this.groupId = '-1';
        this.buy();
      } else {
        //-1单独购买>>0普通拼团>>其他为阶梯拼团ID
        this.groupId = self.isPT(2) ? self.groupConfig.id : 0;
        if (type == 2) {
          this.buy();
        } else {
          $.ajax({
            url: API.validateGroupApi,
            data: {groupId: this.group.id},
            method: 'GET',
            success(res) {
              self.joinGroupId = self.group.id;
              self.buy();
            }
          })
        }
      }
    },

    changeSwiper(e) {
      self.bannerIndex = e.detail.current;
    },
    like() {
      $.ajax({
        url: API.likeGoodsApi,
        data: {
          goodsId: self.id
        },
        method: 'POST',
        success(res) {
          $.$toast(self.i18n['操作成功']);
          self.isLike = !self.isLike;
        }
      })
    },

    getDetail() {
      const self = this
      $.ajax({
        url: API.goodsDetailApi,
        data: {
          goodsId: self.id,
          orderGroupId: self.joinGroupId,
        },
        loading: true,
        method: 'GET',
        success(res) {
          let info = res.data ? res.data : '';
          let goods = info.goods
          let imgArray = goods.goodsImg.split("|")
          self.options.mainImg = goods.mainImg
          self.options.mainImgArray = imgArray
          self.options.title = goods.title
          self.options.price = goods.price
          self.options.trailerLink = goods.trailerLink
          self.recommend = info.recommend
          if (info == '') {
            return
          }
          //查看是否下架
          if (info.goods.status !== 1) {
            uni.showToast({
              title: '此商品未上架',
              duration: 2000
            });
            setTimeout(function () {
              uni.navigateBack();
            }, 2000);
            return;
          }


          self.goods = info.goods;
          self.banner = self.goods.goodsImg.split('|');
          self.goodsParams = info.goodsParams ? info.goodsParams : [];
          // self.skuList = info.goodsSku.skuList ? info.goodsSku.skuList : [];
          // self.skuInfoList = info.goodsSku.attrKeyResultList ? info.goodsSku.attrKeyResultList : [];
          self.shop = info.shop;
          self.isLike = info.isCollectGoods;
          self.fahuo = info.freight ? info.freight : '';
          self.couponList = info.couponList ? info.couponList : [];
          self.now = res.now ? res.now : new Data().getTime();
          self.groupList = info.assembleList ? info.assembleList : [];//拼团列表
          self.pintuanNum = info.pintuanNum ? info.pintuanNum : 0;
          self.groupListConfig = info.groupList ? info.groupList : [];
          // self.setSkuList(self.skuInfoList.length);
          if (self.joinGroupId != '') {//分享链接过来的
            self.group = self.groupList.length > 0 ? self.groupList[0] : '';
            self.isShareGroup = true;
          }
          if (self.isPT() && self.groupList.length > 0) {//判断是否时拼团，并且有人发起，开启定时器
            self.startInterval();
          }
          if (info.goods.type == 2) {//秒杀
            self.startInterval();
            self.caleTime();//计算倒计时间时分秒
          }
          uni.stopPullDownRefresh();
          // #ifdef MP-WEIXIN
          if (self.isRefresh) {
            self.isRefresh = false;
            self.refreshClass = ['fadeIn'];
          }
          // #endif
        }
      })
    },

    startInterval() {
      clearInterval(inter);
      let first = true;
      inter = setInterval(() => {
        self.now += 1000;
        if (self.isMS()) {
          //判断是否时第一次秒杀开始时间
          if (first && self.now >= self.goods.seckillBeginTime && self.now <= self.goods.seckillEndTime) {
            first = false;
            self.caleTime();
          }
        }

      }, 1000)
    },
    caleTime() {
      let time = 0;
      if (self.now < self.goods.seckillBeginTime) {//暂未开始
        time = self.goods.seckillBeginTime;
      } else if (self.now >= self.goods.seckillBeginTime && self.now <= self.goods.seckillEndTime) {
        time = self.goods.seckillEndTime;
      }
      if (time <= 0) {
        return
      }
      ;
      let cha = Math.abs(time - self.now);
      this.day = parseInt(cha / 60 / 60 / 1000 / 24);
      this.hour = parseInt(cha / 60 / 60 / 1000 % 24);
      this.minute = parseInt(cha / 1000 / 60 % 60);
      this.second = parseInt(cha / 1000 % 60);
    },
    init() {
      this.getDetail();
      // this.getCommonList();

    },
  },
  onHide() {
    clearInterval(inter);
  },
  created() {
  },
  computed: {
    i18n() {
      return this.$t('goodsdetail')
    },
  },
  mounted() {
  },
  destroyed() {
  },
  components: {HmCoverCard, couponList, videoIndex},
  onPullDownRefresh() {
    // #ifdef MP-WEIXIN
    this.isRefresh = true;
    this.refreshClass = ['fadeOut'];
    // #endif
    this.$refs.videoList.init();
    this.init();
  },
  onReachBottom() {
  }
}
</script>
